import $ajax from '../../utils/request'
import common from '../../utils/common'

const user = {
    state: {
        user: '', // 用于保存用户信息
        codeInfo: '', // 用于保存健康码信息
        wxLogin: false, // 小程序微信是否调用过登录
        wxOaLogin: false // 公众号微信是否调用过登录
    },

    mutations: {
        SET_USER: (state, user) => {
            let info = state.user
            state.user = {...info, ...user}

        },
        SET_CODEINFO: (state, info) => {
            let codeInfo = state.codeInfo
            state.codeInfo = {...codeInfo, ...info}

        },
        SET_LOGOUT: (state, user) => {
            state.user = ''
        },
        SET_WXLOGIN: (state, wxLogin) => {
            state.wxLogin = wxLogin
        },
        SET_WXOALOGIN: (state, wxLogin) => {
            state.wxOaLogin = wxLogin
        }
    },

    actions: {
        setUser({commit}, user) {
            commit('SET_USER', user)
        },
        setWxLogin({commit}, wxLogin) {
            commit('SET_WXLOGIN', wxLogin)
        },
        setWxOaLogin({commit}, wxLogin) {
            commit('SET_WXOALOGIN', wxLogin)
        },
        loginBySession({commit, state, dispatch}) {
            // 请求登录信息，成功后赋值给user对象
            return new Promise((resolve, reject) => {
                let token = common.getUrlParam('token_enc'),
                    params = token ? {token_enc: token} : {}
                $ajax.get('/index/userInfo', params).then(res => {
                // $ajax.get('/login/testLogin?userId=1', params).then(res => {
                    if (res.data) {
                        dispatch('setUser', res.data)
                    }
                    resolve(res.data)
                }).catch(err => {
                    reject(err)
                })
            })
        },
        loginByWX({commit, state, dispatch}) {
            // 请求小程序微信登录信息，成功后跳转页面
            return new Promise((resolve, reject) => {
                $ajax.post('/login/wxLogin?code=' + common.getCookie('wxCode')).then(res => {
                    dispatch('setWxLogin', true)
                    resolve(res.code)
                }).catch(err => {
                    reject(err)
                })
            })
        },
        loginByWXOa({commit, state, dispatch}, code) {
            // 请求公众号微信登录信息，成功后跳转页面
            return new Promise((resolve, reject) => {
                $ajax.post('/login/wxOaLogin?code=' + code).then(res => {
                    dispatch('setWxOaLogin', true)
                    resolve(res.code)
                }).catch(err => {
                    reject(err)
                })
            })
        }
    }
}

export default user
